/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Collections.ObjectModel;
using System.Data.Objects.DataClasses;
using System.Threading.Tasks;

#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif

#if _LOCALDB
  namespace Oceanside.LocalDB
#else
namespace Oceanside.RemoteDB
#endif
{
    public partial class BUSINESS_DAY
    {
        public static BUSINESS_DAY GetNow(DominicaEntities context)
        {
            BUSINESS_DAY day = null;
            try
            {
                var q = from BD in context.BUSINESS_DAYS
                        where BD.IsComplete == false
                        join SCFG in context.SYSCONFIGS on BD.Id equals SCFG.CurrentBusinessDayId
                        orderby BD.BusinessDayDateStamp descending
                        select BD;

                if (q.Any())
                {
                    day = q.First();
                }
                else
                {
                    day = new BUSINESS_DAY();
                    day.BusinessDayDateStamp = DateTime.Now;
                    context.BUSINESS_DAYS.AddObject(day);
                    context.SaveChanges();
                    SYSCONFIG.Get(context).CurrentBusinessDayId = day.Id;
                    context.SaveChanges();
                }
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
            return day;
        }

        public delegate void BindBusinessDaysCallbackType(List<BUSINESS_DAY> checkouts);

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static void GetBusinessDays(int takeCount, BindBusinessDaysCallbackType callback)
        {
            List<BUSINESS_DAY> runList = null;
            try
            {
                using (DominicaEntities context = new DominicaEntities(DominicaEntities.GetEfConString()))
                {
                    var q = from bd in context.BUSINESS_DAYS.Where(bd=>bd.IsComplete)
                            orderby bd.BusinessDayDateStamp descending
                            select bd;
                    if (q.Any())
                    {
                        runList = q.Take(takeCount).ToList();
                    }
                }
            }
            catch (Exception e)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_REPORT_ERROR, e);
            }
            finally
            {
                try
                {
                    PosWindow.MainPosWindow.Dispatcher.Invoke(callback, runList);
                }
                catch (Exception e)
                {
                    Logging.LogException(e);
                }
            }
        }

        public static List<Int64> GetOpenTables()
        {
            List<Int64> openTables = new List<Int64>();
            using (DominicaEntities context = new DominicaEntities((DominicaEntities.GetEfConString())))
            {
                KIOSK k = KIOSK.Get(context);


                SYSCONFIG sycfg = context.SYSCONFIGS.FirstOrDefault();
                BUSINESS_DAY bd = context.BUSINESS_DAYS.Where(b => b.Id == sycfg.CurrentBusinessDayId).FirstOrDefault();
                foreach (SHIFT shift in bd.SHIFTS)
                {
                    if (!shift.IsComplete)
                    {
                        foreach (ORDER o in shift.ORDERS)
                        {
                            if (!o.IsClosed)
                            {
                                openTables.Add(o.UserId);
                                break;
                            }
                        }
                    }
                }
            }
            return openTables;
        }

        public static List<Int64> CloseBusinessDay_NOTHROW(string weather, string notes)
        {
            List<Int64> openShifts = new List<long>();

            try
            {
                using (DominicaEntities context = new DominicaEntities((DominicaEntities.GetEfConString())))
                {
                    KIOSK k = KIOSK.Get(context);

                    SYSCONFIG sycfg = context.SYSCONFIGS.FirstOrDefault();
                    BUSINESS_DAY bd = context.BUSINESS_DAYS.Where(b => b.Id == sycfg.CurrentBusinessDayId).FirstOrDefault();
                    foreach (SHIFT shift in bd.SHIFTS)
                    {
                        if (!shift.IsComplete)
                        {
                            openShifts.Add(shift.Id);
                        }
                    }

                    ///Close all open shifts
                    foreach (Int64 shiftId in openShifts)
                    {
                        SHIFT shift = context.SHIFTS.Where(si => si.Id == shiftId).FirstOrDefault();
                        SHIFT.CloseShift(context, shift, 0, true);
                    }

                    ///Now that all of the shifts are closed out, we can close the business day.
                    bd.CheckoutDateStamp = DateTime.Now;
                    bd.CloseoutKioskId = k.Id;
                    bd.IsComplete = true;
                    bd.PMNotes = notes;
                    bd.WeatherSummary = weather;
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return openShifts;
        }
    }
}
